#include "frame_thread_pool.h"


static void *threadFunc(void *arg) {
    threadPool_t *threadPool = (threadPool_t *)arg;

    while(1) {
        // 下三个为线程所需资源
        int netfd;

        userOpInfo_t useropinfo;  
        memset(&useropinfo, 0, sizeof(useropinfo));
        useropinfo.mysql = threadPool->mysql;
        strcpy(useropinfo.addr, userSpace);
        
        tlvPacket_t tlv;
        memset(&tlv, 0, sizeof(tlv));

        pthread_mutex_lock(&threadPool->mutex);

        while(threadPool->taskQueue.size == 0 && threadPool->exitFlag == 0) {
            pthread_cond_wait(&threadPool->cond, &threadPool->mutex);
        }

        if(threadPool->exitFlag == 1) {
            printf("\nI am worker. I am going to exit!\n");
            // 子线程退出不用dequeue， 不用关netfd， 主线程帮着关了
            pthread_mutex_unlock(&threadPool->mutex);
            pthread_exit(NULL);
        }

        deQueue(&threadPool->taskQueue, &netfd);
        useropinfo.netfd = netfd;
        printf("\nI am worker, I got netfd = %d\n", netfd);

        useropinfo.ID = threadPool->ID;
        strcpy(useropinfo.userName, threadPool->userName);
        strcpy(useropinfo.opName, threadPool->opName);

        tlv.type = threadPool->type;

        pthread_mutex_unlock(&threadPool->mutex);

        printf("Next, do something!\n");
        printf("\n");

        // work

        int retThread = dealCommand(&useropinfo, &tlv);  
        if(retThread == -1) {
            printf("Error! waiting for next command\n\n");
            continue;
        }
        printf("\n");



        //sleep(20);



        close(netfd);
    }
}

int makeWorker(threadPool_t *threadPool) {
    for(int i = 0; i < threadPool->tidArr.workerNum; i++) {
        pthread_create(&threadPool->tidArr.arr[i], NULL, threadFunc, threadPool);
    }
    return 0;
}
